package com.mail.transfer.email.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author xiaocg
 */
@RestController
public class MailController {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 邮件测试
     * @return
     */
    @GetMapping("/mail")
    public String sendMail(){

        SimpleMailMessage message = new SimpleMailMessage();
        //邮件设置
        message.setSubject("邮件主题");
        message.setText("邮件内容");
        message.setTo("386353564@qq.com");
        message.setFrom("386353564@qq.com");
        javaMailSender.send(message);
        return "简单邮件发送成功！";

    }

    /**
     * 发送附件
     * @return
     * @throws MessagingException
     */
    @GetMapping("/mineMail")
    public String sendMineMail() throws MessagingException {

        //1、创建一个复杂的邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //邮件主题
        helper.setSubject("这是一个邮件啊");
        //文本中添加图片
        helper.addInline("image1",new FileSystemResource("D:\\images\\spring\\1.jpg"));
        //邮件内容
        helper.setText("全栈学习笔记<a href='https://www.cnblogs.com/swzx-1213/'>百度一下</a>    <img src='cid:image1'></img>",true);
        helper.setTo("386353564@qq.com");
        helper.setFrom("386353564@qq.com");
        //附件添加图片
        helper.addAttachment("1.jpg",new File("D:\\images\\spring\\1.jpg"));
        //附件添加word文档
        helper.addAttachment("哈哈哈.docx",new File("D:\\images\\spring\\哈哈哈.docx"));

        javaMailSender.send(mimeMessage);

        return "复杂邮件发送！";
    }
}
